<script setup>
import { ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const username = ref('')
const password = ref('')
const errorMessage = ref('')
const router = useRouter()
const userStore = useUserStore()

const handleLogin = async () => {
  // 非空检查
  if (!username.value.trim()) {
    errorMessage.value = '用户名不能为空';
    return;
  }
  if (!password.value.trim()) {
    errorMessage.value = '密码不能为空';
    return;
  }
  try {
    // 打印发送到后端的数据
    console.log('发送到后端的登录数据:', { username: username.value, password: password.value });
    const response = await fetch('http://localhost:8080/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username: username.value, password: password.value }),
    });

    const responseData = await response.json();
    console.log('完整登录响应数据:', responseData);
    console.log('响应数据结构:', Object.keys(responseData));
    console.log('data字段内容:', responseData.data);
    // 同时检查HTTP状态和后端返回的业务状态
    if (!response.ok || !responseData.success) {
      if (response.status === 500) {
        errorMessage.value = '服务器错误，请稍后再试';
      } else {
        errorMessage.value = responseData.message || '用户账户或密码出错';
      }
      return;
    }
    // 调整数据访问路径，匹配后端响应结构
    const userData = responseData.data.data || responseData.data;
    userData.loginTime = userStore.loginTime; // 添加登录时间到用户数据
    console.log('完整用户数据:', userData);
    console.log('登录用户角色:', userData.role);
    const token = responseData.token || userData.token;
    localStorage.setItem('token', token);
    // 更新Pinia状态
    await userStore.login(userData);
    console.log('登录后Pinia状态:', { isLoggedIn: userStore.isLoggedIn, role: userStore.role, id: userStore.id, username: userStore.username });
    localStorage.setItem('currentUser', JSON.stringify(userData));
    if (userData.status === 'inactive') {
      console.log('重定向到:block');
      router.push('/block');
    } else if (userData.role === '管理员') {
      console.log('重定向到:user-manage');
      router.push('/user-manage').then(() => window.location.reload());
    } else if (userData.role === '用户') {
      console.log('重定向到:main');
      router.push('/main');
    } else if (userData.role === '授权医护人员' || userData.role === '健康管理师') {
      console.log('重定向到:doctor');
      router.push('/doctor');
    } else {
      console.log('未匹配角色:', userData.role);
    }
  } catch (error) {
    console.error('登录错误详情:', error);
    errorMessage.value = '服务器错误，请稍后再试';
  }
};
</script>

<template>
  <div class="login-container">
    <div class="login">
      <h1>登录</h1>
      <div v-if="errorMessage" class="error-message">
        <span class="error-icon">⚠️</span>
        <span class="error-text">{{ errorMessage }}</span>
      </div>
      <input v-model="username" placeholder="用户名" />
      <input v-model="password" type="password" placeholder="密码" />
      <button @click="handleLogin">登录</button>
      <RouterLink to="/register" class="register-link">如果没有账户，请点击此处注册</RouterLink>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
  font-family: 'Arial', sans-serif;
}

.login {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 350px;
}

.login h1 {
    margin-bottom: 15px;
    color: #333;
    text-align: center;
    margin-bottom: 30px;
  }
  .error-message {
    color: #d43f3a;
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
    border-radius: 4px;
    padding: 10px 15px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    animation: fadeIn 0.3s ease-out;
  }
  .error-icon {
    margin-right: 8px;
    font-size: 16px;
  }
  .error-text {
    flex: 1;
  }
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(-5px); }
    to { opacity: 1; transform: translateY(0); }
  }

input {
  width: calc(100% - 24px);
  padding: 12px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

button {
  width: 100%;
  padding: 12px;
  margin-top: 20px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #5a67d8;
}

.register-link {
  display: block;
  margin-top: 15px;
  text-align: center;
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
}

.register-link:hover {
  text-decoration: underline;
}
</style>